import { ref, unref, getCurrentInstance, watch } from 'vue'
import { tryOnUnmounted } from '@vueuse/core'

export function useModal (props) {
  const modalRef = ref(null)
  const currentInstance = getCurrentInstance()

  const register = modalInstance => {
    tryOnUnmounted(() => {
      modalRef.value = null
    })
    modalRef.value = modalInstance
    currentInstance?.emit('register', modalInstance)

    watch(() => props,
      () => {
        props && modalInstance.setProps(props)
      },
      {
        immediate: true,
        deep: true,
      },
    )
  }

  const getInstance = () => {
    const instance = unref(modalRef.value);
    return instance;
  }

  const methods = {
    setProps: (props) => {
      getInstance()?.setProps(props)
    },
    openModal: () => {
      getInstance()?.openModal()
    },
    closeModal: () => {
      getInstance()?.closeModal()
    },
    setModalLoading: (status) => {
      getInstance()?.setModalLoading(status)
    },
  }

  return [register, methods]
}
